package br.com.moxeon.view.composer;

import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Row;
import org.zkoss.zul.Window;

import br.com.vexillum.control.GenericControl;
import br.com.vexillum.model.CommonEntity;
import br.com.vexillum.util.Return;
import br.com.vexillum.view.CRUDComposer;

@SuppressWarnings("serial")
public abstract class BaseComposer<E extends CommonEntity, G extends GenericControl<E>> extends CRUDComposer<E, G> {

	public Row rowAtivo;
	
	protected BaseComposer<E, G> parentComposer;
	
	public BaseComposer<E, G> getParentComposer() {
		return parentComposer;
	}

	public void setParentComposer(BaseComposer<E, G> parentComposer) {
		this.parentComposer = parentComposer;
	}

	
	@SuppressWarnings("unchecked")
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		if(arg.get("selectedEntity") != null){
			entity = (E) arg.get("selectedEntity");
			update = true;			
		}
		setParentComposer((BaseComposer<E, G>) arg.get("thisComposer"));
		disableRowAtivo();
	}
	
	public void disableRowAtivo() {
		Row linha = (Row) getComponentById(component, "rowAtivo");
		
		if(linha != null && !update){
			linha.setVisible(false);
		}
	}
	
	public void callUpdateModal(){
		Return ret = validateSelectedEntity();
		if(ret.isValid()){
			super.callModalWindow(getUpdatePage());
		}
	}
	
	public void callDeactivationConfirmation(){
		super.showDeactivateConfirmation(getDeactivationMessage());
	}
	
	@Override
	public Return saveEntity() {
		Return ret = super.saveEntity();
		if(ret.isValid() && getUpdate()){
			getParentComposer().loadBinder();
			((Window) getComponentById(component, "modalWindow")).detach();
		} else if (ret.isValid()) {
			clearForm();
		}
		loadBinder();
		return ret;
	}
	
	
	protected abstract String getUpdatePage();
	protected abstract String getDeactivationMessage();
	
}
